/*
   Copyright 2011 
   
   DIFED

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package com.difed.cccam.widget;

import java.util.List;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.difed.cccam.R;
import com.difed.cccam.db.ProveedorBD;
import com.difed.cccam.db.ProveedorBDImpl;
import com.difed.cccam.db.entidades.DatosConexion;
import com.difed.cccam.db.entidades.Widget;
import com.difed.cccam.util.CustomLog;

public class WidgetConfigure extends Activity implements OnClickListener {

    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    
    protected List<DatosConexion> conexiones;

    public WidgetConfigure() {
        super();
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        CustomLog.debug("WidgetConfigure", "onCreate");

        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);
        
        // Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        ProveedorBD p = ProveedorBDImpl.getProveedor(this);
        conexiones = p.getConexiones();
        if (conexiones == null || conexiones.isEmpty()) {
            Toast.makeText(this, "No hay conexiones", Toast.LENGTH_LONG).show();
            finish();
        } else {
            // Set the view layout resource to use.
            setContentView(R.layout.widget_configure);
            RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
            
            if (conexiones.size() == 1) {
                DatosConexion dc = conexiones.get(0);
                aceptaConfiguracion(dc.getId());
            } else {
                boolean seleccionado = true;
                int id = 1;
                for (DatosConexion dc : conexiones) {
                    RadioButton rd = new RadioButton(this);
                    rd.setText(dc.getNombre());
                    rd.setId(id++);
                    rd.setTag(dc.getId());
                    rd.setChecked(seleccionado);
                    seleccionado = false;
                    rg.addView(rd);
                }
                
             // Bind the action for the save button.
                findViewById(R.id.config_guardar_widget).setOnClickListener(this);
                findViewById(R.id.config_cancelar_widget).setOnClickListener(this);
                
                setConfigureResult(Activity.RESULT_CANCELED);
            }
        }

        
    }

    @Override
    public void onClick(View v) {
        CustomLog.debug("AemetWidgetConfigure", "onClick");
        if (v.getId() == R.id.config_guardar_widget) {            
            RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
            int idSeleccionado = rg.getCheckedRadioButtonId();
            long idConexion = (Long) rg.findViewById(idSeleccionado).getTag();
            aceptaConfiguracion(idConexion);
        } else if (v.getId() == R.id.config_cancelar_widget) {
            setConfigureResult(Activity.RESULT_CANCELED);
            finish();            
        }
    }

    /**
     * Convenience method to always include {@link #mAppWidgetId} when setting
     * the result {@link Intent}.
     */
    public void setConfigureResult(int resultCode) {
        final Intent data = new Intent();
        data.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(resultCode, data);
    }
    
    private void aceptaConfiguracion(long idConexion) {
        ProveedorBD proveedor = ProveedorBDImpl.getProveedor(this);
        Widget w = new Widget();
        w.setId(mAppWidgetId);
        w.setIdConexion(idConexion);
        w.setConfigurado(true);
        proveedor.guardaWidget(w);

        Intent intent = new Intent(this, UpdateService.class);
        intent.setAction(UpdateService.ACTION_MANUAL_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        startService(intent);
        setConfigureResult(Activity.RESULT_OK);
        finish();
    }
}